<?php
/**
 * Classe che implementa l'interfaccia \Syrius\Adapter\Driver e nascone mysqli
 * @package Adapter
 * @author <domenico.biancardi@gmail.com>
 */

namespace Syrius\Adapter;

class XML extends \DOMDocument implements Driver {

    private $_host;
    private $_dbConnection;

    /**
     * Effettua la connessione ad un database
     * @param string $host
     * @param string $database
     * @param string $username
     * @param string $password
     * @param array $options
     * @throws \Syrius\Exception\Connection_Error
     */
    public function __construct($host) {
        // controllare se il file non esiste e scatenare un'eccezione
        if (!file_exists($host)) {
            throw new Exception("Host $host unknown");
        }
        $this->_host = $host;
    }

    public function setDbConnection($connection) {
        $this->_dbConnection = $connection;
    }

    public function loadModel() {
        $this->load($this->_host);
        $this->readNode($this->documentElement, true,null);
    }

    public function readNode($node, $root, $parentEntity) {
        echo $node->tagName;
        $entity = null;
        $fields = array();
        if (!$root) {
            $class = new $node-> nodeName();
            $fields = $class -> fields();
            $entity = $class->getEntity();
            if ($parentEntity != null && in_array($parentEntity -> getModel() -> source(), array_keys($fields))){
                $entity -> {$parentEntity -> getModel() -> source()} = $parentEntity -> id;
            }
        }
        $childs = $node->childNodes;
        for ($i = 0; $i < $childs->length; $i++) {
            $node = $childs->item($i);
            if ($node->nodeName == "#text") {

            } else {
                if ( $entity != null && in_array($node -> nodeName, array_keys($fields))){
                    $entity -> {$node -> nodeName} = $node -> nodeValue;
                }else{
                    if (!$root){
                        $entity -> save();
                    }
                    $this->readNode($node, false, $entity);
                }
            }
        }
        if (!$root)
            $entity -> save();

    }

    public function saveModel() {
        echo $this->saveXML();
    }

    public function select_db($dbname) {
        return;
    }

}

?>
